package intelligentcity.model.traffic;

import intelligentcity.conf.Conf;
import intelligentcity.loggers.TimeCounter;
import intelligentcity.model.City;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class Traffic extends Thread {

    private final City city;
    private final static AtomicInteger counter = new AtomicInteger(0);
    private ConcurrentHashMap<Integer, Car> cars;
    private final TimeCounter timeCounter;

    public Traffic(City city, int numberOfCars) {
        this.city = city;
        this.timeCounter = new TimeCounter();
        timeCounter.start();
        cars = new ConcurrentHashMap<>();
        for (int i = 0; i < numberOfCars; i++) {
            int number = counter.getAndIncrement();
            cars.put(number, new Car(city, this, number));
        }
        for (Integer i : cars.keySet()) {
            cars.get(i).start();
        }
    }

    @Override
    public void run() {
        while (true) {
            Conf.stop(Conf.timeBetweenNewCarCreating);
            int myCounter = counter.getAndIncrement();
            Car car = new Car(city, this, myCounter);
            cars.put(myCounter, car);
            car.start();
        }
    }

    public ConcurrentHashMap<Integer, Car> getCars() {
        return cars;
    }

    public City getCity() {
        return city;
    }

    public TimeCounter getTimeCounter() {
        return timeCounter;
    }
}
